import React, { useEffect, useMemo, useState } from 'react'
import Taro from '@tarojs/taro'
import { View,ScrollView,Image, Input } from '@tarojs/components'
import citySelect from './citySelect.js';
import './index.scss'

export default function FansSelect(props) {
  let {cityClick = ()=>{},placeholder = '请输入城市名称',formatName='cityName',isSearch=true,obtainCitys=[],hotCity=[],activeCity} = props
  const [toView,setToView] = useState('city-letter-Find')
  const [scrollTop,setscrollTop] = useState(0)
  const [cityindexs,setcityindexs] = useState([])
  const [activeCityIndex,setactiveCityIndex] = useState('')
  const [handleCity,sethandleCity] = useState([])
  const [serachCity,setserachCity] = useState('')
  useEffect(()=>{
    if (obtainCitys && obtainCitys.length) {
      initializationCity();
    }
  },[obtainCitys])
  function handleTop(){
    const query = Taro.createSelectorQuery()
    setscrollTop(0)
    setTimeout(() => {
      query.select('#city-letter-1').boundingClientRect(data => {
        data ? (setscrollTop(data.top)) : void 0
      }).exec()
    }, 0)
  }
  const sortItems = useMemo(()=>{  /// 城市列表排序
    for (let index = 0; index < handleCity.length; index++) {
      if (handleCity[index].isCity) {
        let cityArr = handleCity[index].citys;
        cityArr = cityArr.sort(function(a, b) {
          var value1 = a.unicode;
          var value2 = b.unicode;
          return value1 - value2;
        });
      }
    }
    return handleCity;
  },[handleCity])

  /**
   * @desc 初始化城市数据
   * @return undefind
   */
  function initializationCity() {
    let arr = []
    const cityLetterArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'];
    for (let index = 0; index < cityLetterArr.length; index++) {
      arr.push({
        name: cityLetterArr[index],
        isCity: false, // 用于区分是否含有当前字母开头的城市
        citys: [], // 存放城市首字母含是此字母的数组
        forName: 'city-letter-' + (cityLetterArr[index] == '#' ? '0' : cityLetterArr[index]) //label的绑定
      });
    }
    buildCityindexs(arr)
  }
  /**
   * @desc 构建城市索引
   * @return undefind
   */
  function buildCityindexs(value) {
    let handleCity = [...value]
    let arr = []
    for (let i = 0; i < obtainCitys.length; i++) {
      // 获取首字母
      const cityLetter = getLetter(obtainCitys[i][formatName]).firstletter;
      // 获取当前城市首字母的unicode，用作后续排序
      const unicode = getLetter(obtainCitys[i][formatName]).unicode;

      const index = cityIndexPosition(cityLetter);
      if (arr.indexOf(cityLetter) === -1) {
        handleCity[index].isCity = true;
        arr.push(cityLetter);
      }
      handleCity[index].citys.push({
        cityName: obtainCitys[i][formatName],
        unicode: unicode,
        oldData: obtainCitys[i]
      });
    }
    setcityindexs(arr)
    sethandleCity(handleCity)
  }

  /**
   * @desc 得到城市的首字母
   * @param str String
   */
  function getLetter(str) {
    return citySelect.getFirstLetter(str[0]);
  }
  
  /**
   * @desc 滑动到城市索引所在的地方
   * @param id String 城市索引
   */
  function cityindex(id) {
    setToView(id)
  }

  /**
   * @desc 获取城市首字母的unicode
   * @param letter String 城市索引
   */
  function cityIndexPosition(letter) {
    if (!letter) {
      return '';
    }
    const ACode = 65;
    return letter === '#' ? 26 : letter.charCodeAt(0) - ACode;
  }
  
  /** @desc 城市列表点击事件
   *  @param Object
   */
  function cityTrigger(item) {
    // 传值到父组件
    cityClick(item.oldData ? item.oldData : item)
  }

  const searchDatas = useMemo(()=>{  // 搜索后的城市列表
    var searchData = [];
    for (let i = 0; i < obtainCitys.length; i++) {
      if (obtainCitys[i][formatName].indexOf(serachCity) !== -1) {
        searchData.push({
          oldData: obtainCitys[i],
          name: obtainCitys[i][formatName]
        });
      }
    }
    return searchData;
  },[])
  return (
    <View className="city-select">
      <ScrollView scroll-top={scrollTop} scroll-y className="city-select-main" id="city-select-main" scroll-into-view={toView}>
        {isSearch?<View className="city-serach"><Input onInput={e=>{
          setserachCity(e.target.value)
        }} placeholder={placeholder} className="city-serach-input" /></View>:null}
        {activeCity && !serachCity?<>
          <View className="hot-title" id="city-letter-1">当前选择</View>
          <View className="hot-city">
          <View className="hot-item dot" style="display: flex;align-items: center;justify-content: center;
    white-space: nowrap;" onClick={()=>{cityTrigger(activeCity)}}>
            <Image src={require('@/static/location.png')} style="width: 24rpx;margin-right: 8rpx" mode="widthFix"></Image>
            { activeCity[formatName] }
          </View>
        </View>
        </>:null}
        
        {hotCity.length > 0 && !serachCity?<>
        <View className="hot-title">热门城市</View>
        <View className="hot-city">
          {hotCity.map((item,index)=>{
            return <View key={index} onClick={()=>{cityTrigger(item, 'hot')}} className="hot-item">{ item[formatName] }</View>
          })}
        </View>
        </>:null}
        {!serachCity?
        <View className="citys">
          {sortItems?.map((city,index)=>{
            return city.isCity?<View key={index} className="citys-row">
            <View className="citys-item-letter" id={'city-letter-' + (city.name === '#' ? '0' : city.name)}>{ city.name }</View>
            {city.citys?.map((item,inx)=>{
              return <View className="citys-item" key={inx} onClick={()=>{cityTrigger(item)}}>{ item.cityName }</View>
            })}
          </View>:null
          })}
        </View>:
        <View className="citys">
          {searchDatas?.map((item,index)=>{
            return <View key={index} className="citys-row">
            <View className="citys-item" key="index" onClick={()=>{cityTrigger(item)}}>{ item.name }</View>
          </View>
          })}
        </View>}
      </ScrollView>
      {!serachCity?
      <View className="city-indexs-view">
        <View className="city-indexs">
          <View className="city-indexs-text" onClick={()=>{handleTop()}}>当前</View>
          <View className="city-indexs-text" onClick={()=>{handleTop()}}>热门</View>
          {handleCity?.map((cityIns, index)=>{
            return cityIns.isCity?<View className="city-indexs-text" key={index} onClick={()=>{cityindex(cityIns.forName)}}>
            { cityIns.name }
          </View>:null
          })}
        </View>
      </View>:null}
    </View>
  )
}
